import {getMoment} from "../../utils/moment";
import store from "../../store";
export function getProdStatus(start, end, translate = true, form = 'YYYY-MM-DD HH:mm:ss') {
    let stateObject = {
        type: 0, 
        times: 0 ,
    }
    if (start && end) {
        if (translate) {
            start = getMoment(start, form).valueOf()
            end = getMoment(end, form).valueOf()
        } else {
            start = parseInt(start)
            end = parseInt(end)
        }
        let date = new Date()
        let current = date.getTime() 
        if (current < start) { 
			stateObject.msg = '距开始'
            stateObject.times = start - current 
        } else if (current < end) { 
            stateObject.type = 1
			stateObject.msg = '距结束'
            stateObject.times = end - current 
        } else { 
			stateObject.msg = '活动已结束'
            stateObject.type = 2
        }
        return stateObject
    } else {
        return {
            type: 3,
            times: 0
        }
    }
}

export function formatStockList(list, isCart,min_num) {
    if (list && list.length > 0) {
        let cartList = store.state.vuex_cart_list
        return list.map(item => {
            item = {
                ...item,
                max_num: item.max_num ? parseInt(item.max_num) : 0,
                min_num:min_num,
                name: item.name,
                pk_id: item.pk_id,
                purchase_quantity: item.purchase_quantity ? parseInt(item.purchase_quantity) : 0,
                stock_num: item.stock_num ? parseInt(item.stock_num) : 0,
                cartNum: getCartNum(item.pk_id, cartList),
				amount:item.r_price || item.r_price === 0? item.r_price : item.amount, 
				rebate:item.r_rebate || item.r_rebate === 0?item.r_rebate : item.rebate
            }
            return getStockMaxAndMinNum(item, isCart,min_num) 
        })
    } else {
        return []
    }
}


function getCartNum(stockId, cartList) {
    if (cartList && cartList.length > 0) {
        let cartItem = cartList.find(item => item.attr_id === stockId)
        return cartItem ? cartItem.num : 0
    } else {
        return 0
    }
}

export function getStockMaxAndMinNum(item, isCart = false) {
    
    if (item.max_num === 0) { 
        item.max_num = item.stock_num - item.purchase_quantity
    } else {
		
        item.max_num = item.max_num - item.purchase_quantity
        if (item.max_num > item.stock_num) item.max_num = item.stock_num
    }
    if (!isCart) {
		
		item.max_num -= item.cartNum
	}
    if (item.max_num <= 0) { 
        item.max_num = 0
        item.min_num = 0
    }
    
    if (item.min_num === 0 && item.max_num > 0) {
        item.min_num = 1
    } else {
        item.min_num = item.min_num <= item.max_num ? item.min_num : item.max_num
    }
    return item
}
